﻿#include "itemadd.h"
#include "ui_itemadd.h"

ItemAdd::ItemAdd(QWidget *parent, const QString &table) :
    QDialog(parent),_table(table),
    ui(new Ui::ItemAdd)
{
    ui->setupUi(this);

    ui->lbl_rate->setText("0");
}

ItemAdd::~ItemAdd()
{
    delete ui;
}

bool ItemAdd::addItem(const QString &label, const QString &tag, int rate,
                      const QString &detail, const QString &addition)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (label,tag,rate,detail,addition) values (?,?,?,?,?)").arg(_table));
    query.addBindValue(label);
    query.addBindValue(tag);
    query.addBindValue(rate);
    query.addBindValue(detail);
    query.addBindValue(addition);

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemAdd::on_btn_submit_clicked()
{
    QString label=ui->label->text().trimmed();
    QString tag=ui->tag->text().trimmed();
    if(label.isEmpty() || tag.isEmpty())
        return;

    int rate=ui->rate->value();
    QString detail=ui->detail->toPlainText();
    QString addition=ui->addition->text().trimmed();
    if(!addItem(label,tag,rate,detail,addition))
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
    else
        accept();
}

void ItemAdd::on_rate_valueChanged(int value)
{
    ui->lbl_rate->setText(QString::number(value));
}
